package controllers;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import utils.YUtils;

import models.Contract;
import models.Project;
import models.User;
import flexjson.transformer.DateTransformer;


/**
 * 
 */

public class Projects extends Application {
  
    public static void index() {
        render();
    }

    /**
     * Get Records json.
     */
    public static void json(int page, int pagesize) {    	
    	List<Project> projects = Project.find("byDept", connectedUser().dept)
    			.fetch(page, pagesize);       
        long total = Project.count("byDept", connectedUser().dept);
        
        HashMap<String,Object> obj = new HashMap<String,Object>();
        obj.put("Rows", projects);
        obj.put("Total", total);
        renderJSON(obj);
    }


    /**
     * Add a Record.
     */
    public static void add(Project project) {
    		User u = connectedUser();
    		if(project.user==null){
    			project.dept=u.dept;
            	project.user=u;
    		}
            project.save();
            ok();
    }
    
    /**
     * Update a Record.
     */
    public static void save(Project project) {
        project.save();
        ok();
    }
    
    /**
     * Delete a Record.
     */
    public static void delete(long id) {
        Project.findById(id)._delete();
        ok();
    }
    
    /**
     * load contract conllection
     */
    public static void getContract(Long projectId){
		List<Contract> contracts = Contract.find("project.id=?",projectId).fetch();
		String contractList = Contract.toJson(contracts);
		String jsonStr = YUtils.ligerGridData(contractList, contracts.size());
		renderJSON(jsonStr);
    }
    
    public static void serach(String productName,String contractUnit){
		List<Project> projects = Project.serachByNameContractUnit(productName, contractUnit, connectedUser().dept);
		HashMap<String, Object> obj = new HashMap<String, Object>();
		obj.put("Rows", projects);
		obj.put("Total", projects.size());
		renderJSON(obj);
    }
	
	/**
     * Approve Record.
     */
    public static void approve(int type) {        
        render();
    }   
    
}

